package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 配置全局过滤器
 * @Author WSJ
 * @Date 2022-03-11-16:23
 * @Version 1.0 （版本号）
 */
@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器的执行逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否包含登录/login,是的话直接放行
        if (request.getURI().getPath().contains("/login")) {
            return chain.filter(exchange);
        }
        //取出需要鉴权的token
        String token = request.getHeaders().getFirst("token");
        //如果token不存在，直接返回未授权状态
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token，验证是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i==0||i==-1) {
                //token有效，获取用户id和用户名，并存在请求头中转发到后续的微服务中
                Object userId = claims.get("userId");
                Object userName = claims.get("userName");
                request.mutate().header("userId",userId.toString());
                request.mutate().header("userName",userName.toString());
                //放行
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //记录日志
            log.error(e.getMessage());
        }
        //未知异常，一律返回401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器的执行顺序，数字越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
